import React from 'react'
import { Form, Input, Button, message } from 'antd'
import { useNavigate, Navigate } from 'react-router-dom'
import { getMenu } from '../../api'
import './login.css'

const Login = () => {

  const navigate = useNavigate()

  // 在登陆状态下需要跳转到home页面
  if (sessionStorage.getItem('token')) {
    return <Navigate to='/home' replace />
  }

  const handleSubmit = (val) => {
    if (!val.password || !val.username) {
      return message.open({
        type: 'warning',
        content: '请输入账号、密码'
      })
    }
    getMenu(val).then(({ data }) => {
      switch (data.code) {
        case 200:
          sessionStorage.setItem('token', data.data.token)
          sessionStorage.setItem('menu', JSON.stringify(data.data.menu))
          message.open({
            type: 'success',
            content: data.data.message,
          })
          navigate('/home')
          break;
        case -999:
          return message.open({
            type: 'error',
            content: data.message,
          })
        default:
          return message.open({
            type: 'warning',
            content: '网络延迟，请稍后再试',
          })
      }
    })
  }

  return (
    <Form className="login-container" onFinish={handleSubmit}>
      <div className="login-title">系统登录</div>
      <Form.Item
        label="账号"
        name="username"
      >
        <Input placeholder='请输入账号' />
      </Form.Item>
      <Form.Item
        label="密码"
        name="password"
      >
        <Input.Password placeholder='请输入密码' />
      </Form.Item>
      <Form.Item className="login-button">
        <Button type='primary' htmlType='submit'>登录</Button>
      </Form.Item>
    </Form>
  )
}

export default Login;